const { watch, series, src, dest } = require('gulp')
const { resolve, extname, dirname } = require('path')
var rename = require('gulp-rename')
const gulp = require('gulp')

const sfsFolder = resolve(
  '/Users/i073349/Workspace/trunk/tomcat-sfs/webapps/ROOT'
)
const suffix = '_dev-snapshot'

const globs = [
  '/Users/i073349/Workspace/trunk/au-goalmanagement/au-goalmanagement-web/src/main/webapp/ui/gm/**/*.js',
]

function watchFiles(cb) {
  let watcher = watch(globs)
  watcher.on('change', function(path, stats) {
    let relatedPath = path.split('/webapp/')[1]
    let targetPath = resolve(sfsFolder, relatedPath).toString()
    let extName = extname(targetPath)
    let dist = dirname(targetPath)
    let finalTargetPath = targetPath.replace(extName, suffix + extName)
    console.log({ path, finalTargetPath })
    src(path)
      .pipe(
        rename(function(p) {
          p.basename += suffix
        })
      )
      .pipe(dest(dist))
  })
}

exports.default = series(watchFiles)
